angular.module('webmac.service',['ngSanitize'])
.constant('jconfig',{
     api_base:(location.hostname=='localhost' || location.hostname.indexOf('i.jobdeer.com')!=-1)?"http://git.api.i.jobdeer.com/":"http://api.jobdeer.com/",
     pwd: 'admin'
})
.config(function($httpProvider,$provide){
    //接管报错
    var error_log_times = 0;
    $provide.decorator("$exceptionHandler", function($delegate,$injector){
        return function(exception, cause){
            var $http = $injector.get('$http');
            if('undefined'==typeof(navigator) || !navigator.userAgent){
                var browser='不支持navigator.userAgent';
            }else{
                var browser=navigator.userAgent;
            }
            //同一人触发了10次报警就不在报警
            if(error_log_times<10){
                // $http.post('http://jdlog.vipsinaapp.com/log',{msg:'<h3>前端JS错误</h3>'+'错误信息：'+exception.stack+',<br />用户浏览器：'+browser+'<br />访问地址：'+location.href,type:'js_error',site:'jdapi',send_mail:1});
                error_log_times++;
            }
            $delegate(exception, cause);
        };
    });
    //对php的post处理
    $httpProvider.defaults.transformRequest = function(request){
     if(typeof(request)!='object'){
            return request;
     }
     var str = [];
     for(var k in request){
        if(k.charAt(0)=='$'){
                delete request[k];
                 continue;
        }
       var v='object'==typeof(request[k])?JSON.stringify(request[k]):request[k];
       str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
     }
     return str.join("&");
   };
   $httpProvider.defaults.timeout=10000;
   $httpProvider.defaults.headers.post = {
        'Content-Type': 'application/x-www-form-urlencoded'
   };
   $httpProvider.responseInterceptors.push('interceptor');

})
.factory('interceptor',function($q,jconfig,$injector){
    return function(promise){
       return promise.then(function(response){
            if('object'!=typeof(response.data)){
                if(0===response.config.url.indexOf(jconfig.api_base)){
                    //如果请求接口返回的内容不是json数据，则报错
                    alert('服务出错，请稍后再试!');
                    console.log(response);
                    return $q.reject({code:-3,messge:"response format error"});
                }
                return response;
            }
            //如果返回错误码, 标记为错误
            if(response.data.code){

                //常见错误处理
                if(response.data.code){
                    if('10001'==response.data.code){

                        alert(response.data.message);
                        response.data.code=-1;
                        return $q.reject(response);
                    }
                    if('10002'==response.data.code){
                        if(!window.error10002){
                            //只报错一次
                            window.error10002=true;
                            alert('权限错误，请重新登录',function(){
                                window.error10002=false;
                            });
                        }
                        //错误码在设置为小于0，避免重复判断错误
                        response.data.code=-2;
                        return $q.reject(response);
                    }
                    if('10003'==response.data.code){

                        if(!window.error10003){
                             //只报错一次
                             window.error10003=true;
                             alert('登录超时，请重新登录',function(){
                                  window.error10003=false;
                             });
                        }
                        //错误码在设置为小于0，避免重复判断错误
                        response.data.code=-3;
                        return $q.reject(response);
                    }
                    if('30001'==response.data.code){
                        alert('数据库出错');
                        response.data.code=-4;
                        return $q.reject(response);
                    }
                    if('99999'==response.data.code){
                        var message=response.data.message.replace('其他 -','');
                        alert(message);
                        response.data.code=-5;
                        return $q.reject(response);
                    }
                }
                //调用接口错误
                return $q.reject(response);
            }
            //去除错误码，只返回数据部分
            if('undefined'!=typeof(response.data.data)){
                //对引号处理，因为接口为了安全已经转移了引号， angularjs前端为了安全会转义& 符合
                var parse_quote=function(data){
                    var json=JSON.stringify(data)
                       .replace(/&quot;/g,'\\"')
                       .replace(/&#039;/g,"'")
                       .replace(/&ldquo;/g,'“')
                       .replace(/&rdquo;/g,'”')
                       .replace(/&lsquo;/g,'‘')
                       .replace(/&rsquo;/g,'’');
                       return JSON.parse(json);

                };
                response.data=parse_quote(response.data.data);
            }
            return response;
        },function(response){

            if(response.config.url.indexOf('noerror')==-1){
                //一些请求频率比较高的接口，如信息检查，每个几秒钟就请求的接口，出错几率打，出错时可以不显示错误，只要url上待noerror即可
                alertify.alert('服务器端出错');
            }
            response.data={
               code:-6,
               message:response
            };
           return $q.reject(response);
        });
    };
})
//JobDeer 工具
.factory('$jd',function($http,jconfig,$timeout,$location){
    return {
        apiurl:function(url){
            return jconfig.api_base+url;
        },
        get:function(url){
            var url = this.apiurl(url);
            return $http.get(url);
        },
        post:function(url,param){
            var url = this.apiurl(url);
            return $http.post(url,param);
        },
        //监听请求条件的变化，可以间隔自动刷新列表
        watch:function(scope,timeout,change_search){
            if('undefined'==typeof(change_search)){
                //是否改变url的querystring
                change_search=false;
            }
            var success_cb=function(data){};
            var error_cb=function(data){};
            var cb={
                success:function(func){
                    //设置成功的回调函数
                    success_cb=func;
                    return cb;
                },
                error:function(func){
                    //设置失败的回调函数
                    error_cb=func;
                    return cb;
                },
                reload:function(){
                    run();
                }
            };

            if(!scope.request){
                alert('watch 方法没有指定scope.request');
                return ;
            }

            if(!scope.request.url){
                alert('watch 方法没有指定scope.request.url');
                return ;
            }

            if(!scope.request.params){
                 scope.request.params={};
            }

            scope.request.reload=function(){
                run();
            };

            var self=this;
            var run=function(){
                 var url=self.apiurl(scope.request.url);
                 if(url.indexOf('?')==-1){
                    url+='?'+$.param(scope.request.params)
                 }else{
                    url+='&'+$.param(scope.request.params)
                 }
                 $http.get(url).success(success_cb).error(error_cb);
                 if(change_search){
                     $location.search(scope.request.params);
                 }
            };
            scope.$watch('request',run,true);

            if(timeout){
                timeout = timeout*1000;
                //如果设置了timeout，会实时刷新
                cancelRefresh = $timeout(function myFunction() {
                    run();
                    cancelRefresh = $timeout(myFunction, timeout);
                },timeout);

                //切换到其他页面后，终止自动刷新
                scope.$on('$destroy', function(e) {
                            $timeout.cancel(cancelRefresh);
                });
            }
            return cb;
        }
    };
})

.factory('$os',function(){
    return {
        size : function(){
            var winHeight, winWidth;
            //获取窗口宽度
            if (window.innerWidth)
                winWidth = window.innerWidth;
            else if ((document.body) && (document.body.clientWidth))
                winWidth = document.body.clientWidth;
            //获取窗口高度
            if (window.innerHeight)
                winHeight = window.innerHeight;
            else if ((document.body) && (document.body.clientHeight))
                winHeight = document.body.clientHeight;
            //通过深入Document内部对body进行检测，获取窗口大小
            if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth){
                winHeight = document.documentElement.clientHeight;
                winWidth = document.documentElement.clientWidth;
            }
            return {
                width: winWidth,
                height: winHeight
            };
        }
    }
})

.filter('show_email_suffix',function(){
    return function(email){
       return  '*@'+email.split('@')[1];
    };
})

.filter('default',function(){
    return function(data,default_value){
        return data?data:default_value;
    };
})
.filter('undefined',function(){
    return function(data){
        return 'undefined'==typeof(data);
    };
})

.filter('empty',function(){
    return function(data){
        if('undefined'==typeof(data)){
            return false;
        }
        return data?false:true;
    };
})

.filter('unsafe', ['$sce', function ($sce) {
    return function (val) {
        return $sce.trustAsHtml(val);
    };
}])

.filter('jdate',function($filter){
    return function(date,format){
        var arr = date.split(/[- :]/),
        time = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
        //转换字符串为时间戳再格式化
        //为什么不用 Date.parse(str) 直接转换字符串为时间戳,  因为 Date.parse 支持的字符串时间格式有限，容易返回NaN
       return $filter('date')(time.getTime(), format);
    };
})

.filter('cut_str',function(){
    return function(str,length){
       if('string'!=typeof(str))
          return str;
       var end = str.length>length?'...':'';
       return str.substr(0,length)+end;
    };
})

.directive('jpage',function(){
    return {
        restrict:"EA",
        replace:true,
        template:'<ul class="pagination" ng-if="show"><li ng-click="go({page:1})"><a href="javascript:void(0);" title="首页">&laquo;</a></li><li ng-repeat="page in pages"  ng-class="{active:page==currentpage}"  ng-click="go({page:page})"><a href="javascript:void(0);">{{page}}</a></li><li ng-click="go({page:totalpage})"><a href="javascript:void(0);" title="尾页">&raquo;</a></li></ul>',
        scope:{
            //总页数
            totalpage:"=",
            //当前页数
            currentpage:"=",
            //显示分页个数,默认为10
            size:"=",
            //分页回调函数,传递参数page
            go:"&"
        },
        controller:function($scope,$element,$attrs,$transclude)
        {
            var run=function(){
                var totalpage=parseInt($scope.totalpage);
                //要有两页才显示分页
                $scope.show=totalpage>1?true:false;
                if(!$scope.show)
                    return ;
                var currentpage=parseInt($scope.currentpage);
                var size=$scope.size?parseInt(size):10;
                var half_size=parseInt((size+1)/2);
                var start_page=currentpage-half_size;
                if(start_page<1){
                    half_size+=Math.abs(start_page);
                    start_page=1;
                }
                var end_page=currentpage+half_size;
                if(end_page>totalpage){
                    var start_page=start_page-(end_page-totalpage);
                    if(start_page<1)
                        start_page=1;
                    end_page=totalpage;
                }
                var pages=[];
                for(i=start_page;i<=end_page;i++){
                    pages.push(i);
                }
                $scope.pages=pages;
                $scope.totalpage=totalpage;
                $scope.currentpage=currentpage;
            };
            $scope.$watch('totalpage+currentpage',function(){
                //计算更改pages变量
                run();
            });
        }
    };
})
;
